package com.xinlan;

import com.xinlan.model.User;
import io.smallrye.mutiny.Uni;
import io.vertx.mutiny.sqlclient.Pool;
import io.vertx.mutiny.sqlclient.Tuple;
import jakarta.inject.Inject;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;

/**
 * 用户资源
 *
 * @author 92110
 * @date 2025/10/17 01:43
 * @description
 */
@Path("/user")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class UserResource {

    @Inject Pool client;

    @POST
    @Path("/add")
    public Uni<Result<Long>> addUser(User user) {
        return client.withTransaction(connection ->
                        connection.preparedQuery("INSERT INTO user (name, age, sex) VALUES (?,?,?)")
                                .execute(Tuple.of(user.name, user.age, user.sex))
                                .onItem().transform(rowSet -> {
                                    // 获取插入的ID（如果数据库支持返回生成的ID）
                                    Long generatedId = null;
                                    if (rowSet.iterator().hasNext()) {
                                        generatedId = rowSet.iterator().next().getLong(0);
                                    }
                                    return Result.success("用户添加成功", generatedId);
                                })
                )
                .onFailure().recoverWithItem(throwable -> {
                    // 记录错误日志
                    System.err.println("用户添加失败: " + throwable.getMessage());
                    return Result.error(400, "用户添加失败: " + throwable.getMessage());
                });
    }
}
